<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    

<script>
// 生成 [min-max] 的随机整数
function randomInt(min,max){
    return Math.round(Math.random()*(max-min))+min;
}

// 封装一个函数，随机生成十六进制颜色字符串 如 '#3e3e3e'
// 16进制数：0 1 2 3 4 5 6 7 8 9 a b c d e f
function randomColor(){
    var color = '#';
    var str = '0123456789abcdef';
    for (var i = 0; i < 6; i++){
        var index = randomInt(0,15);// 生成0-15的随机整数
        color += str[index];
    }
    return color;
}
// console.log( randomColor() );// '#64ac44'
// console.log( randomColor() );// '#ef5853'

// 封装一个函数，随机生成x位验证码（字母数字组合）如 '2L3mn5'
function randomCode(x){
    // 设置x的默认值
    x = x || 6;
    // ASCII码值范围：48-122（除了58-64和91-96这两个范围）
    var code = '';
    for (var i = 0; i < x; i++) {
        do {
            var ascii = randomInt(48,122);// 生成48-122的随机整数
        } while((ascii >= 58 && ascii <= 64) || (ascii >= 91 && ascii <= 96));
        code += String.fromCharCode(ascii);
    }
    return code;
}
console.log( randomCode() );
console.log( randomCode(4) );
console.log( randomCode(8) );

</script>
</body>
</html>